package javabase.schoolwork.day6_1to3;

/**
 * @author fance
 * @date 2018/6/1 20:03
 */
public class MyList<T> {
    class Node<T> {
        T val;
        Node next;
        Node(T val) {
            this.val = val;
        }
    }

    private Node<T> head = null;




    /**
     * 插入数据
     * @param value
     */
    public void add(T value) {
        Node newNode = new Node(value);
        if (head == null) {
            head = newNode;
            return;
        }

        Node tmp = head;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = newNode;
    }
    public T get(int index) {
        if (index < 1 || index > this.length()) {
            return null;
        }
        int i = 1;
        Node<T> curNode = head;
        while (curNode != null) {
            if (i == index) {
                return curNode.val;
            }
            curNode = curNode.next;
            i++;
        }

        return null;
    }
    public boolean remove(int index) {
        if (index < 1 || index > this.length()) {
            return false;
        }
        // 删除第一个
        if (index == 1) {
            head = head.next;
            return true;
        }
        int i = 1;
        Node preNode = head;
        Node curNode = preNode.next;
        while (curNode != null) {
            if (i == index) {
                preNode.next = curNode.next;
                return true;
            }
            preNode = curNode;
            curNode = curNode.next;
            i++;
        }

        return false;
    }
    public int length() {
        Node tmp = head;
        int cnt = 0;
        while (tmp != null) {
            tmp = tmp.next;
            cnt++;
        }
        return cnt;
    }
    public void printList() {
        Node tmp = head;
        while (tmp != null) {
            System.out.print(tmp.val + " ");
            tmp = tmp.next;
        }
        System.out.println();
    }


}
